<template>

    <div class="login-container">

      <el-card class="login-card">

        <h1 class="login-title">苍蓝星系统登录</h1>

        <div class="login-form">

          <el-form :model="loginForm" @submit.prevent="handleLogin">

            <el-row>
                <el-col :span="24">
                    <el-form-item label="用户名" label-width="60px">
                        <el-input v-model="loginForm.username" autocomplete="off" prefix-icon="user" maxlength="10" show-word-limit></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="密 码" label-width="60px">
                        <el-input type="password" v-model="loginForm.password" autocomplete="off" prefix-icon="lock" show-password></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="16">
                    <el-form-item label="验证码" label-width="60px">
                        <el-input v-model="loginForm.captcha" autocomplete="off" prefix-icon="check"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <!-- 绑定点击事件来更新验证码图片 -->
                    <img :src="captchaUrl" @click="updateCaptcha" class="captcha-image" alt="验证码">
                </el-col>
            </el-row>
        
            <el-form-item>
                <el-button type="primary" @click="handleLogin">登录</el-button>
            </el-form-item>
           
          </el-form>
          <RouterView />
        </div>

        <!-- 无帐号，点此注册 -->
        <el-row style="text-align: right;">
          <el-col>
            <el-text class="w-150px mb-2">
              若无帐号，点此>> <RouterLink to="/register" style="font-size: 1.2em;">注册</RouterLink>
            </el-text>
          </el-col>
        </el-row>
        
      </el-card>
    </div>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import { RouterLink } from 'vue-router';
import { useRouter } from 'vue-router';
import { getCaptcha,validateCaptcha,login } from '@/api/captcha';
import { usePhoneStore } from '../stores/phone';
import { getPhoneNumberByUsername } from '@/api/register';

const captchaUrl = ref('');

onMounted(() => {
  updateCaptcha();
});

// 更新验证码的函数
function updateCaptcha() {
  getCaptcha().then(url => {
    captchaUrl.value = url;
  });
}

// 定时更新验证码
setInterval(updateCaptcha, 300000); // 每5分钟更新一次验证码

const loginForm = ref({
  username: '',
  password: '',
  captcha: ''
});

const router = useRouter();
const phoneStore = usePhoneStore(); // 使用 Pinia store

function handleLogin() {
  console.log('登录信息:', loginForm.value);

  // 验证验证码
  validateCaptcha({ captcha: loginForm.value.captcha })
    .then(captchaResponse => {

      console.log('验证码验证结果:', captchaResponse);

      if (captchaResponse === true) {
        console.log(loginForm.value.username)
        console.log(loginForm.value.password)
        // 验证码验证成功后，发送登录请求
        login({
          username: loginForm.value.username,
          password: loginForm.value.password
        })
          .then(loginResponse => {
            console.log('登录结果:', loginResponse);
            if (loginResponse === true) {
              // 登录成功后跳转到 home 页面
              console.log("loginResponse:", loginResponse);
              //将用户名，密码作为参数传递至后端，调用getPhoneNumberByUsername
              getPhoneNumberByUsername(loginForm.value.username, loginForm.value.password)
              .then(res => {
                if (res.data.code === 200) {
                const phone = res.data.data.phone;
                // 将手机号作为信息缓存
                phoneStore.setPhone(phone);

                router.push("/home");
                }
              });


              
              //将手机号作为信息缓存
            } else {
              console.error('登录失败:', loginResponse.data.message || '无错误信息');
            }
          })
          .catch(loginError => {
            console.error('登录请求出错:', loginError);
          });
      } else {
        console.error('验证码验证失败:', captchaResponse.data.message || '无错误信息');
      }
    })
    .catch(error => {
      console.error('验证码验证出错:', error);
    });
}



</script>
  
<style scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-image: url('@/assets/imgs/1.jpg'); /* 假设背景图片在assets目录下 */
    background-size: cover;
    background-position: center;
  }
  
  .login-card {
    width: 420px;
    padding: 20px;
    background-size: cover;
    background-position: center;
    background-color: rgba(255, 255, 255, 0.8); /* 半透明白色背景 */
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }
  .login-title {
    text-align: center;
    margin-bottom: 20px;
    color: #409eff;
  }
  .login-form {
    width: 100%;
  }

  .captcha-image {
    cursor: pointer; /* 当鼠标悬停时显示为可点击状态 */
    margin-left: 10px; /* 与输入框保持一定间距 */
    height: 36px; /* 控制图片高度，根据实际情况调整 */
    vertical-align: middle; /* 垂直居中对齐 */
}
</style>